import React = require("react");
import { BasePage } from "controls/base-page";
import { PageProps } from "maishu-chitu-react";
import { ItemDialog, ItemDialogState } from "controls/item-dialog";
import { ActivityService } from "services/activity";
import { ProductSelectDialog } from "controls/product-select-dialog";
import { ShoppingService } from "services/shopping";
import { buttonOnClick } from "maishu-ui-toolkit";
import { FormValidator, rules as r } from "maishu-dilu";
import site from "site";
import { url } from "inspector";
import { guid } from "maishu-chitu-service";

interface Props extends PageProps {
    data: {
        id: string
    }
}

interface State {
    promotions?: Promotion[]
}

const promotionTypeTexts = {
    Reduce: '满减',
    Given: '满赠',
    Discount: '满折'
};

const promotionMethodTexts = {
    Amount: '按商品总金额',
    Count: '按商品总数量'
};

const objectTypeTexts = {
    Brand: '品牌',
    Category: '类别',
    Product: '商品'
}

const promotionTypes = {
    amount: 'Reduce',
    product: 'Given',
    discount: 'Discount'
};

const promotionMethods = {
    amount: 'Amount',
    count: 'Count'
};

let objectNames: { [key: string]: string } = {};

export default class ActivityEditPage extends BasePage<Props, State> {
    private promotionDialog: PromotionDialog;
    private activityService: ActivityService;
    private productDialog: ProductDialog;
    private brandDialog: BrandDialog;
    private categoryDialog: CategoryDialog;
    private givenDialog: BuyGivenDialog;
    private reduceDialog: BuyReduceDialog;
    private discountDialog: BuyDiscountDialog;

    constructor(props) {
        super(props)

        this.state = {};
        this.activityService = this.props.createService(ActivityService);

    }

    newProductRule(promotion: Promotion) {
        let rule = { ObjectType: "Product", PromotionId: promotion.Id, CollectionType: "Include" } as PromotionRangeRule;
        this.productDialog.show(rule as PromotionRangeRule, "添加商品", (item) => {
            promotion.PromotionRangeRules.push(item);
            this.setState(this.state);
        })
    }

    newBrandRule(promotion: Promotion) {
        let rule = { ObjectType: "Brand", PromotionId: promotion.Id, CollectionType: "Include" } as PromotionRangeRule;
        this.brandDialog.show(rule as PromotionRangeRule, "添加品牌", (item) => {
            promotion.PromotionRangeRules.push(item);
            this.setState(this.state);
        })
    }

    newCategoryRule(promotion: Promotion) {
        let rule = { ObjectType: "Category", PromotionId: promotion.Id, CollectionType: "Include" } as PromotionRangeRule;
        this.categoryDialog.show(rule as PromotionRangeRule, "添加类别", (item) => {
            promotion.PromotionRangeRules.push(item);
            this.setState(this.state);
        })
    }

    /** 满减 */
    newBuyReduce(promotion: Promotion, rule?: PromotionContentRule) {
        if (rule == null)
            rule = { PromotionId: promotion.Id } as PromotionContentRule;

        this.reduceDialog.show({ promotion, rule }, "满减");
    }

    /** 满折 */
    newBuyDiscount(promotion: Promotion, rule?: PromotionContentRule) {
        if (rule == null)
            rule = { PromotionId: promotion.Id } as PromotionContentRule;

        this.discountDialog.show({ promotion, rule }, "满折");
    }

    /** 满赠 */
    newBuyGiven(promotion: Promotion, rule?: PromotionContentRule) {
        if (rule == null)
            rule = { PromotionId: promotion.Id } as PromotionContentRule;

        this.givenDialog.show({ promotion, rule }, "满赠", ({ promotion, rule }) => {
            rule.Description = this.description(promotion, rule);
            if (!rule.Id) {
                rule.Id = guid();
                promotion.PromotionContentRules.push(rule);
            }
            this.setState(this.state)
        });
    }


    getConditionText(promotion: Promotion, promotionRule: PromotionContentRule) {
        var condition_text;
        if (promotion.Method == promotionMethods.count) {
            condition_text = `购买指定商品任意 ${promotionRule.LevelValue} 件, `;
        }
        else if (promotion.Method == promotionMethods.amount) {
            condition_text = `购买指定商品满 ￥${new Number(promotionRule.LevelValue).toFixed(2)} 元, `;
        }
        return condition_text;
    }

    description(promotion: Promotion, contentRule: PromotionContentRule) {
        if (promotion.Type == promotionTypes.product) {
            var str = '即可获赠';// chitu.Utility
            let items = contentRule.GivenValue.split(",").map(o => {
                let arr = o.split(":");
                let id = arr[0];
                let quantity = Number.parseInt(arr[1]);
                return { id, quantity };
            });

            for (var i = 0; i < items.length; i++) {
                if (i > 0)
                    str = str + "，";

                str = str + ` “${objectNames[items[i].id]}” ${items[i].quantity} 件`;
            }

            let description = this.getConditionText(promotion, contentRule) + str;
            return description;
        }
        else if (promotion.Type == promotionTypes.amount) {
            let str = `￥${new Number(contentRule.GivenValue).toFixed(2)}`;
            var given_text = `即减 ${str} 元`;
            return this.getConditionText(promotion, contentRule) + given_text;
        }
        else if (promotion.Type == promotionTypes.discount) {
            var given_text = `打 ${contentRule.GivenValue} 折`;
            return this.getConditionText(promotion, contentRule) + given_text;
        }
    }


    showContentRuleDialog(promotion: Promotion, rule?: PromotionContentRule) {
        switch (promotion.Type) {
            case promotionTypes.amount:
                this.newBuyReduce(promotion, rule);
                break;
            case promotionTypes.discount:
                this.newBuyDiscount(promotion, rule);
                break;
            case promotionTypes.product:
                this.newBuyGiven(promotion, rule);
                break;
        }
    }

    removeRangeRule(p: Promotion, c: PromotionRangeRule): void {
        p.PromotionRangeRules = p.PromotionRangeRules.filter(o => o.Id == c.Id);
        this.setState(this.state);
    }

    removeContentRule(p: Promotion, c: PromotionContentRule) {
        p.PromotionContentRules = p.PromotionContentRules.filter(o => o.Id == c.Id);
        this.setState(this.state);
    }

    componentDidMount() {
        this.activityService.promotions(this.props.data.id).then(r => {
            this.setState({ promotions: r });
        })
    }

    renderButtns() {
        return [
            <button className="btn btn-sm btn-primary">
                <i className="icon-save"></i>
                <span>保存</span>
            </button>,
            <button className="btn btn-sm btn-primary"
                onClick={() => this.promotionDialog.show({ Method: "Amount", Type: "Given" } as Promotion, "添加优惠",
                    (item) => {
                        let id = this.props.data.id;
                        return this.activityService.addPromotion(id, item.Type, item.Method);
                    })
                }>
                <i className="icon-plus"></i><span>添加优惠</span>
            </button>,

        ]
    }

    renderView() {
        let { promotions } = this.state;
        if (promotions == null) {
            return site.loadingElement;
        }
        return <>
            {promotions.map(p => <React.Fragment key={p.Id}>
                <div className="row">
                    <div className="col-md-6">
                        <table className="table table-striped table-bordered table-hover" style={{ borderCollapse: "collapse" }}>
                            <thead>
                                <tr>
                                    <th colSpan={4}>优惠范围</th>
                                </tr>
                                <tr>
                                    <th style={{ textAlign: "center", width: 60 }}>类型</th>
                                    <th style={{ textAlign: "center" }}>名称</th>
                                    <th style={{ textAlign: "center", width: 160 }}>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {p.PromotionRangeRules.length == 0 ?
                                    <tr data-bind="visible:ko.unwrap(rules).length == 0">
                                        <td colSpan={4} style={{ border: 0, textAlign: "center" }}>
                                            <div style={{ padding: "50px 0px 50px 0px" }}>
                                                <b>暂无优惠商品</b>
                                                <div>可以勾选"全场优惠"或者点击"添加商品"按钮添加要优惠的商品</div>
                                            </div>
                                        </td>
                                    </tr>
                                    : p.PromotionRangeRules.map(c =>
                                        <tr key={c.Id}>
                                            <td>{objectTypeTexts[c.ObjectType]}</td>
                                            <td>{c.ObjectName}</td>
                                            <td className="text-center">
                                                <label className="switch">
                                                    <input type="checkbox" className="ace ace-switch ace-switch-5"
                                                        checked={c.CollectionType == "Include"}
                                                        onChange={e => {
                                                            c.CollectionType = e.target.checked ? "Include" : "Exclude";
                                                            this.setState({ promotions })
                                                        }} />
                                                    <span className="lbl middle"></span>
                                                </label>
                                                <button className="btn btn-minier btn-danger" style={{ marginLeft: 4 }}
                                                    ref={e => {
                                                        buttonOnClick(e, async () => this.removeRangeRule(p, c), { confirm: `是否删除 ${c.ObjectName} 吗` })
                                                    }}>
                                                    <i className="icon-trash"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    )
                                }
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colSpan={3} className="">
                                        <div className="pull-left">
                                            <label>
                                                <input data-bind="checked:allProducts" type="checkbox" checked={p.IsAll}
                                                    onChange={e => {
                                                        p.IsAll = e.target.checked;
                                                        this.setState({ promotions })
                                                    }} />&nbsp; 全场优惠
                                            </label>
                                        </div>
                                        <div className="pull-right">
                                            <button className="btn btn-primary btn-sm" onClick={() => this.newProductRule(p)}>添加商品</button>
                                            <button className="btn btn-primary btn-sm" onClick={() => this.newBrandRule(p)}>添加品牌</button>
                                            <button className="btn btn-primary btn-sm" onClick={() => this.newCategoryRule(p)}>添加品类</button>
                                        </div>
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                    <div className="col-md-6">
                        <table className="table table-striped table-bordered table-hover" style={{ borderCollapse: "collapse" }}>
                            <thead>
                                <tr>
                                    <th colSpan={4}>优惠内容</th>
                                </tr>
                                <tr>
                                    <th style={{ textAlign: "center" }}>名称</th>
                                    <th style={{ textAlign: "center", width: 100 }}>
                                        <span>{p.Method == "Amount" ? "金额" : "数量"}</span>
                                    </th>
                                    <th style={{ textAlign: "center", width: 80 }}>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {p.PromotionContentRules.length == 0 ?
                                    <tr data-bind="visible:ko.unwrap(rules).length==0">
                                        <td colSpan={4} style={{ border: 0, textAlign: "center" }}>
                                            <div style={{ padding: "50px 0px 50px 0px" }}>
                                                <b>暂无优惠内容</b>
                                                <div>可以点击"添加优惠内容"按钮,添加优惠内容</div>
                                            </div>
                                        </td>
                                    </tr> :
                                    p.PromotionContentRules.map(c =>
                                        <tr key={c.Id}>
                                            <td>{c.Description}</td>
                                            <td style={{ textAlign: "right" }}>
                                                {p.Method == "Amount" ? "￥" + c.LevelValue.toFixed(2) : c.LevelValue}
                                            </td>
                                            <td style={{ textAlign: "center" }}>
                                                {/* <button className="btn btn-minier btn-info" title="点击编辑优惠内容"
                                                    onClick={() => this.showContentRuleDialog(p, c)}>
                                                    <i className="icon-pencil"></i></button> */}
                                                <button className="btn btn-minier btn-danger"
                                                    onClick={e => this.removeContentRule(p, c)}
                                                    ref={e => {
                                                        if (!e) return
                                                        buttonOnClick(e, async () => this.removeContentRule(p, c), { confirm: `确定删除 '${c.Description}' 吗` })
                                                    }}>
                                                    <i className="icon-trash" />
                                                </button>
                                            </td>
                                        </tr>
                                    )
                                }
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colSpan={4}>
                                        <div className="pull-left">
                                            <div>
                                                <label>
                                                    <span style={{ fontWeight: 'bold' }}>优惠方式：</span>
                                                    <span data-bind="text:methodText">{promotionMethodTexts[p.Method]}</span>
                                                </label>
                                                <label style={{ paddingLeft: 10 }}>
                                                    <span style={{ fontWeight: 'bold' }}>优惠类型：</span>
                                                    <span data-bind="text:typeText">{promotionTypeTexts[p.Type]}</span>
                                                </label>
                                            </div>
                                        </div>
                                        <div className="pull-right">
                                            <button className="btn btn-primary btn-sm"
                                                onClick={() => this.showContentRuleDialog(p)}>添加优惠内容</button>
                                        </div>
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>

            </React.Fragment>)
            }
            <PromotionDialog ref={e => this.promotionDialog = e || this.promotionDialog} />
            <ProductDialog ref={e => this.productDialog = e || this.productDialog} />
            <BrandDialog {...this.props} ref={e => this.brandDialog = e || this.brandDialog} />
            <CategoryDialog {...this.props} ref={e => this.categoryDialog = e || this.categoryDialog} />
            <BuyGivenDialog ref={e => this.givenDialog = e || this.givenDialog} />
            <BuyReduceDialog ref={e => this.reduceDialog = e || this.reduceDialog} />
            <BuyDiscountDialog ref={e => this.discountDialog = e || this.discountDialog} />
        </>
    }

}

class PromotionDialog extends ItemDialog<{}, Promotion> {
    constructor(props) {
        super(props)

    }
    render() {
        let item = this.state.item;
        return <>
            <div className="form-group clearfix">
                <label className="control-label col-sm-2">
                    *优惠方式
                </label>
                <div className="col-sm-10">
                    <label className="radio-inline">
                        <input name="promotion_type" type="radio" checked={item.Method == "Amount"}
                            onChange={e => {
                                if (!e.target.checked) return;

                                item.Method = "Amount";
                                this.setState({ item });
                            }} />
                        <span>按金额优惠</span>
                    </label>
                    <label className="radio-inline">
                        <input name="promotion_type" type="radio" checked={item.Method == "Count"}
                            onChange={e => {
                                if (!e.target.checked) return;

                                item.Method = "Count";
                                this.setState({ item });
                            }} />
                        <span>按购买商品总数</span>
                    </label>
                </div>
            </div>
            <div className="form-group clearfix">
                <label className="control-label col-sm-2">
                    *优惠类型
                </label>
                <div className="col-sm-10">
                    <label className="radio-inline">
                        <input name="promotion_method" type="radio" checked={item.Type == "Given"}
                            onChange={e => {
                                if (!e.target.checked) return;

                                item.Type = "Given";
                                this.setState({ item });

                            }} />
                        <span>满赠</span>
                    </label>
                    <label className="radio-inline">
                        <input name="promotion_method" type="radio" checked={item.Type == "Reduce"}
                            onChange={e => {
                                if (!e.target.checked) return;

                                item.Type = "Reduce";
                                this.setState({ item });

                            }} />
                        <span>满减</span>
                    </label>
                    <label className="radio-inline">
                        <input name="promotion_method" type="radio" checked={item.Type == "Discount"}
                            onChange={e => {
                                if (!e.target.checked) return;

                                item.Type = "Discount";
                                this.setState({ item });
                            }} />
                        <span>满折</span>
                    </label>
                </div>
            </div>
        </>
    }
}

class ProductDialog extends ItemDialog<{}, PromotionRangeRule> {
    constructor(props) {
        super(props)

        this.confirmButtonText = "确定";
    }
    render() {
        let item = this.state.item;
        return <>
            <div className="form-group clearfix">
                <label className="control-label col-sm-2">
                    *商品名称
                </label>
                <div className="col-sm-10">
                    <div className="input-group">
                        <input className="form-control" placeholder="请输入产品编号"
                            style={{ display: "none" }}
                            value={item.ObjectId || ""}
                            onChange={e => {
                                item.ObjectId = e.target.value;
                                this.setState({ item })
                            }} />

                        <input className="form-control" placeholder="请选择商品"
                            value={item.ObjectName || ""} readOnly={true} />

                        <span className="input-group-btn">
                            <button name="btnSelectProduct" className="btn btn-default" type="button"
                                title="点击选择商品"
                                onClick={() => ProductSelectDialog.show((items) => {
                                    item.ObjectId = items[0].Id;
                                    item.ObjectName = items[0].Name;
                                    this.setState({ item });
                                })}>
                                <i className="icon-cog" />
                            </button>
                        </span>
                    </div>
                </div>
            </div>
            <div className="form-group clearfix">
                <div className="col-sm-10 col-sm-offset-2">
                    <label className="radio-inline">
                        <input name="productType" type="radio" checked={item.CollectionType == "Include"}
                            onChange={e => {
                                if (!e.target.checked) return;
                                item.CollectionType = "Include";
                                this.setState({ item });
                            }} />包含
                                </label>
                    <label className="radio-inline">
                        <input name="productType" type="radio" checked={item.CollectionType == "Exclude"}
                            onChange={e => {
                                if (!e.target.checked) return;
                                item.CollectionType = "Exclude";
                                this.setState({ item });

                            }} />排除
                    </label>
                </div>
            </div>
        </>
    }
}


type BrandDialogState = ItemDialogState<PromotionRangeRule> & { brands?: Brand[] };
class BrandDialog extends ItemDialog<PageProps, PromotionRangeRule, BrandDialogState> {
    private OBJECT_ID: keyof PromotionRangeRule = "ObjectId"
    shoppingService: ShoppingService;
    constructor(props) {
        super(props);
        this.confirmButtonText = "确定";
        this.shoppingService = this.props.createService(ShoppingService);
    }
    componentDidMount() {
        this.shoppingService.brands().then(r => {
            this.setState({ brands: r.dataItems });
        })

        this.validator = new FormValidator(this.element,
            { name: this.OBJECT_ID, rules: [r.required("请选择品牌")] }
        )
    }
    render() {
        let { item, brands } = this.state;
        brands = brands || [];
        return <>
            <div className="form-group clearfix">
                <label className="control-label col-sm-2">
                    *品牌
                </label>
                <div className="col-sm-10">
                    <select name={this.OBJECT_ID} className="form-control" value={item.ObjectId || ""}
                        onChange={e => {
                            if (e.target.value) {
                                item.ObjectId = e.target.value;
                                item.ObjectName = brands.filter(o => o.Id == e.target.value)[0].Name;
                            }
                            else {
                                item.ObjectId = "";
                                item.ObjectName = "";
                            }

                            this.setState({ item });
                        }}>
                        <option value="">请选择品牌</option>
                        {brands.map(c =>
                            <option key={c.Id} value={c.Id}>{c.Name}</option>
                        )}
                    </select>
                </div>
            </div>
            <div className="form-group clearfix">
                <div className="col-sm-10 col-sm-offset-2">
                    <label className="radio-inline">
                        <input name="productType" type="radio" checked={item.CollectionType == "Include"}
                            onChange={e => {
                                if (!e.target.checked) return;
                                item.CollectionType = "Include";
                                this.setState({ item });
                            }} />
                        <span>包含</span>
                    </label>
                    <label className="radio-inline">
                        <input name="productType" type="radio" checked={item.CollectionType == "Exclude"}
                            onChange={e => {
                                if (!e.target.checked) return;
                                item.CollectionType = "Exclude";
                                this.setState({ item });
                            }} />
                        <span>排除</span>
                    </label>
                </div>
            </div>
        </>
    }
}

type CategoryDialogState = ItemDialogState<PromotionRangeRule> & { categories?: ProductCategory[] };
class CategoryDialog extends ItemDialog<PageProps, PromotionRangeRule, CategoryDialogState> {
    shoppingService: ShoppingService;
    constructor(props) {
        super(props);

        this.confirmButtonText = "确定";
        this.shoppingService = this.props.createService(ShoppingService);
    }
    componentDidMount() {
        this.shoppingService.categories().then(r => {
            this.setState({ categories: r });
        })
    }
    render() {
        let { item, categories } = this.state;
        categories = categories || [];
        return <>
            <div className="form-group clearfix">
                <label className="control-label col-sm-2">
                    *类别
                </label>
                <div className="col-sm-10">
                    <select className="form-control" value={item.ObjectId || ""}
                        onChange={e => {
                            if (e.target.value) {
                                item.ObjectId = e.target.value;
                                item.ObjectName = categories.filter(o => o.Id == e.target.value)[0].Name;
                            }
                            else {
                                item.ObjectId = "";
                                item.ObjectName = "";
                            }
                            this.setState({ item });
                        }}>
                        <option value="">请选择类别</option>
                        {categories.map(c =>
                            <option key={c.Id} value={c.Id}>{c.Name}</option>
                        )}
                    </select>
                </div>
            </div>
            <div className="form-group clearfix">
                <div className="col-sm-10 col-sm-offset-2">
                    <label className="radio-inline">
                        <input name="productType" type="radio" checked={item.CollectionType == "Include"}
                            onChange={e => {
                                if (!e.target.checked) return;
                                item.CollectionType = "Include";
                                this.setState({ item });
                            }} />
                        <span>包含</span>
                    </label>
                    <label className="radio-inline">
                        <input name="productType" type="radio" checked={item.CollectionType == "Exclude"}
                            onChange={e => {
                                if (!e.target.checked) return;
                                item.CollectionType = "Exclude";
                                this.setState({ item });
                            }} />
                        <span>排除</span>
                    </label>
                </div>
            </div>
        </>
    }
}

abstract class ContentRuleDialog
    extends ItemDialog<{}, { promotion: Promotion, rule: PromotionContentRule }> {

    private LEVEL_VALUE = "LevelValue";

    constructor(props) {
        super(props);

        this.confirmButtonText = "确定";
    }

    componentDidMount() {
        this.validator = new FormValidator(this.element,
            { name: this.LEVEL_VALUE, rules: [r.required(() => this.state.item.promotion.Method == "Count" ? "请选择购买数量" : "请输入消费金额")] }
        );
    }

    abstract renderGiven(): React.ReactElement<any,any>;

    render() {
        let item = this.state.item;
        if (item.promotion == null || item.rule == null) {
            return site.loadingElement;
        }
        let method = item.promotion.Method;
        let rule = item.rule;
        return <>
            {method == "Count" ?
                <div className="form-group clearfix" style={{ display: method == "Count" ? null : 'none' }} >
                    <label className="control-label col-sm-2">*购买数量</label>
                    <div className="col-sm-10">
                        <select name={this.LEVEL_VALUE} className="form-control" value={rule.LevelValue}
                            onChange={e => {
                                rule.LevelValue = Number.parseInt(e.target.value);
                                this.setState({ item });
                            }}>
                            <option value="">请选择购买数量</option>
                            <option value={1}>任意1件</option>
                            <option value={2}>任意2件</option>
                            <option value={3}>任意3件</option>
                            <option value={4}>任意4件</option>
                            <option value={5}>任意5件</option>
                            <option value={6}>任意6件</option>
                            <option value={7}>任意7件</option>
                            <option value={8}>任意8件</option>
                        </select>
                    </div>
                </div> :
                <div className="form-group clearfix" style={{ display: method == "Amount" ? null : 'none' }}>
                    <label className="control-label col-sm-2">*消费金额</label>
                    <div className="col-sm-10">
                        <div className="input-group">
                            <input name={this.LEVEL_VALUE} className="form-control" placeholder="请输入消费金额"
                                value={rule.LevelValue || ""}
                                onChange={e => {
                                    rule.LevelValue = Number.parseFloat(e.target.value);
                                    this.setState({ item });
                                }} />
                            <div className="input-group-addon">元</div>
                        </div>
                        <span className={`${FormValidator.errorClassName} ${this.LEVEL_VALUE}`} style={{ display: "none" }} />
                    </div>
                </div>}
            {this.renderGiven()}
        </>
    }
}


/** 满赠优惠对话框 */
class BuyGivenDialog extends ContentRuleDialog {
    private GIVEN_VALUE: keyof PromotionContentRule = "GivenValue";

    componentDidMount() {
        super.componentDidMount();
        this.validator.appendField({ name: this.GIVEN_VALUE, rules: [r.required("最少选择一个商品")] })
    }
    renderGiven(): React.ReactElement<any,any> {
        let { item } = this.state;
        let givenProducts = (item.rule.GivenValue || "").split(",").filter(o => o).map(o => {
            let arr = o.split(":");
            return { productId: arr[0], count: parseInt(arr[1]) }
        })
        return <>
            <div className="form-group clearfix">
                <label className="control-label col-sm-2">*赠送商品</label>
                <div className="col-sm-10">
                    {givenProducts.map((o, i) =>
                        <div key={o.productId} className="row" style={{ marginBottom: 6 }}>
                            <div className="col-sm-8" style={{ paddingRight: 0 }}>
                                <input className="form-control" readOnly={true} value={objectNames[o.productId] || o.productId} />
                            </div>
                            <div className="col-sm-4" style={{ paddingLeft: 0 }}>
                                <div className="input-group">
                                    <select className="form-control" value={o.count}
                                        onChange={e => {
                                            let g = givenProducts.filter(c => c.productId == o.productId)[0];
                                            g.count = Number.parseInt(e.target.value);
                                            item.rule.GivenValue = givenProducts.map(o => `${o.productId}:${o.count}`).join(",");
                                            this.setState({ item });
                                        }}>
                                        <option value="1">1 件</option>
                                        <option value="2">2 件</option>
                                        <option value="3">3 件</option>
                                        <option value="4">4 件</option>
                                        <option value="5">5 件</option>
                                        <option value="6">6 件</option>
                                        <option value="7">7 件</option>
                                        <option value="8">8 件</option>
                                        <option value="9">9 件</option>
                                    </select>
                                    <span className="input-group-btn">
                                        <button className="btn btn-default" type="button"
                                            onClick={() => {
                                                givenProducts = givenProducts.filter(c => c.productId != o.productId);
                                                item.rule.GivenValue = givenProducts.map(o => `${o.productId}:${o.count}`).join(",");
                                                this.setState({ item });
                                            }}>
                                            <i className="icon-minus"></i>
                                        </button>
                                    </span>
                                </div>
                            </div>
                        </div>
                    )}
                    <div className="form-group" style={{ paddingTop: 8, paddingBottom: 12 }}>
                        <div className="input-group">
                            <input className="form-control" readOnly={true} placeholder="请选择商品" />
                            <span className="input-group-btn">
                                <button className="btn btn-default" type="button" title="点击选择商品"
                                    onClick={() => {
                                        ProductSelectDialog.show((items) => {
                                            for (let i = 0; i < items.length; i++) {
                                                objectNames[items[i].Id] = items[i].Name;
                                                let p = givenProducts.filter(o => o.productId == items[i].Id)[0];
                                                if (p)
                                                    continue;

                                                p = { productId: items[i].Id, count: 1 };
                                                givenProducts.push(p);
                                            }
                                            item.rule.GivenValue = givenProducts.map(o => `${o.productId}:${o.count}`).join(",");
                                            this.setState({ item });
                                        })
                                    }}>
                                    <i className="icon-cog"></i>
                                </button>
                            </span>
                        </div>
                        <input name={this.GIVEN_VALUE} type="hidden" value={item.rule.GivenValue || ""} readOnly={true} />
                        <span className={`${FormValidator.errorClassName} ${this.GIVEN_VALUE}`} style={{ display: "none" }}></span>
                    </div>
                </div>
            </div>
        </>
    }
}


class BuyReduceDialog extends ContentRuleDialog {

    private GIVEN_VALUE: keyof PromotionContentRule = "GivenValue";

    componentDidMount() {
        super.componentDidMount();
        this.validator.appendField({ name: this.GIVEN_VALUE, rules: [r.numeric("请输入正确的金额")] })
    }
    renderGiven(): React.ReactElement<any,any> {
        let { item } = this.state;

        return <div key="reduceAmount" className="form-group">
            <label className="control-label col-sm-2">*减免金额</label>
            <div className="col-sm-10">
                <div className="input-group">
                    <input name={`${this.GIVEN_VALUE}`} className="form-control" placeholder="请输入减免金额"
                        value={item.rule.GivenValue || ""}
                        onChange={e => {
                            item.rule.GivenValue = e.target.value;
                            this.setState({ item });
                        }} />
                    <div className="input-group-addon">元</div>
                </div>
                <span className={`${FormValidator.errorClassName} ${this.GIVEN_VALUE}`} />
            </div>
        </div>
    }
}


class BuyDiscountDialog extends ContentRuleDialog {
    renderGiven(): React.ReactElement<any,any> {
        let { rule } = this.state.item;
        let arr = (rule.GivenValue || "").split(".");
        let [pricePercentMain, pricePercentMinor] = arr;
        pricePercentMain = pricePercentMain || "9";
        pricePercentMinor = pricePercentMinor || "0"
        return <div className="form-group clearfix">
            <label className="control-label col-sm-2">*打折</label>
            <div className="col-sm-10">
                <div className="row">
                    <div className="col-xs-6" style={{ paddingRight: 0 }}>
                        <select data-bind="value:pricePercentMain" className="form-control"
                            value={pricePercentMain}
                            onChange={e => {
                                pricePercentMain = e.target.value;
                                rule.GivenValue = `${pricePercentMain}.${pricePercentMinor}`;
                                this.setState(this.state);
                            }}>
                            <option value="9">9</option>
                            <option value="8">8</option>
                            <option value="7">7</option>
                            <option value="6">6</option>
                            <option value="5">5</option>
                            <option value="4">4</option>
                            <option value="3">3</option>
                            <option value="2">2</option>
                            <option value="1">1</option>
                        </select>
                    </div>
                    <div className="col-xs-6" style={{ paddingLeft: 0 }}>
                        <div className="input-group">
                            <select className="form-control" value={pricePercentMinor}
                                onChange={e => {
                                    pricePercentMinor = e.target.value;
                                    rule.GivenValue = `${pricePercentMain}.${pricePercentMinor}`;
                                    this.setState(this.state);
                                }}>
                                <option value="0">0</option>
                                <option value="1">1</option>
                                <option value="2">2</option>
                                <option value="3">3</option>
                                <option value="4">4</option>
                                <option value="5">5</option>
                                <option value="6">6</option>
                                <option value="7">7</option>
                                <option value="8">8</option>
                                <option value="9">9</option>
                            </select>
                            <div className="input-group-addon">
                                折
                        </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    }

}



